String
Introduction
String is
probably the most commonly used class in Java’s class library. The obvious
reason for this is that strings are a very important part of programming. The
first thing to understand about strings is that every string you create is
actually an object of type String. Even string constants are actually String
objects.
For example, in the statement the string
"This is a String, too" is a String object.
System.out.println("This
is a String, too");
The second thing to understand about strings
is that objects of type String are immutable; once a String object
is created, its contents cannot be altered. While this may seem like a serious
restriction, it is not, for two reasons:
• If you need to change a string, you can
always create a new one that contains the modifications.
• Java defines peer classes of String,
called StringBuffer and StringBuilder, which allow strings to be
altered, so all of the normal string manipulations are still available in
Java.
Strings
can be constructed in a variety of ways. The easiest is to use a statement like
this:
String myString =
"this is a test";
Once
you have created a String object, you can use it anywhere that a string
is allowed.
For
example, this statement displays myString:
System.out.println(myString);
Java
defines one operator for String objects: +. It is used to
concatenate two strings. For example, the following statement results in myString
containing "I like Java."
String myString =
"I" + " like " + "Java.";
The
following program demonstrates the preceding concepts:
Example 15.1: Creating strings
// Demonstrating
Strings.
class StringDemo
{
public
static void main(String args[]) {
String strOb1 = "First String";
String strOb2 = "Second String";
String strOb3 = strOb1 + " and " + strOb2;
System.out.println(strOb1);
System.out.println(strOb2);
System.out.println(strOb3);
}
}
Here are a few. You can test two strings for
equality by using equals( ). You can obtain the length of a string by
calling the length( ) method. You can obtain the character at a
specified index within a string by calling charAt( ). The general forms
of these three methods are shown here:
boolean equals(secondStr);
int length( );
char charAt(index);
Here
is a program that demonstrates these methods.
Example 15.2: Manipulating strings
// Demonstrating
some String methods.
class StringDemo2
{
public
static void main(String args[]) {
String strOb1 = "First String";
String strOb2 = "Second String";
String strOb3 = strOb1;
System.out.println("Length of strOb1: " +
strOb1.length());
System.out.println("Char at index 3 in strOb1: " +
strOb1.charAt(3));
if(strOb1.equals(strOb2))
System.out.println("strOb1 == strOb2");
else
System.out.println("strOb1 != strOb2");
if(strOb1.equals(strOb3))
System.out.println("strOb1 == strOb3");
else
System.out.println("strOb1 != strOb3");
}
}
Of
course, you can have arrays of strings, just like you can have arrays of any
other type of object.
Example 15.3: Collection of strings
// Demonstrate
String arrays.
class StringDemo3
{
public
static void main(String args[]) {
String str[] = { "one", "two",
"three" };
for(int i=0; i<str.length; i++)
System.out.println("str[" + i + "]: " +
str[i]);
}
}
Command
line argument
Sometimes you will want to pass information
into a program when you run it. This is accomplished by passing command-line
arguments to main( ). A command-line argument is the information
that directly follows the program’s name on the command line when it is executed.
To access the command-line arguments inside a Java program is quite easy—they are
stored as strings in a String array passed to the args parameter
of main( ). The first command-line argument is stored at args[0],
the second at args[1], and so on.
For example, the following program displays
all of the command-line arguments that it is called with:
Example 15.4: Creating strings as
arguments in Java’s main()
class CommandLine
{
public
static void main(String args[]) {
for(int i=0; i<args.length; i++)
System.out.println("args[" + i + "]: " + args[i]);
}
}
Constructors in class String
Constructor |
Description |
String() |
Initializes a newly created String object so that it
represents an empty character sequence. |
String(byte[] bytes) |
Constructs a new String by decoding the specified
array of bytes using the platform's default charset. |
Constructs a new String by decoding the specified
array of bytes using the specified charset. |
|
String(byte[] ascii,
int hibyte) |
This method does not properly convert bytes into characters. As
of JDK 1.1, the preferred way to do this is via
the String constructors that take a Charset, charset name, or
that use the platform's default charset. |
String(byte[] bytes,
int offset, int length) |
Constructs a new String by decoding the specified
subarray of bytes using the platform's default charset. |
String(StringBuffer buffer) |
Allocates a new string that contains the sequence of characters
currently contained in the string buffer argument. |
String(StringBuilder builder) |
Allocates a new string that contains the sequence of characters
currently contained in the string builder argument. |
String(byte[] bytes,
int offset, int length, Charset charset) |
Constructs a new String by
decoding the specified subarray of bytes using the specified charset. |
String(byte[] ascii, int hibyte,
int offset, int count)Deprecated. |
This method does not properly convert bytes
into characters. As of JDK 1.1, the preferred way to do this is via the String constructors
that take a Charset, charset name, or that use the platform's default
charset. |
String(byte[] bytes, int offset,
int length, String charsetName) |
Constructs a new String by decoding
the specified subarray of bytes using the specified charset. |
Constructs a new String by
decoding the specified array of bytes using the specified charset. |
|
String(char[] value) |
Allocates a new String so that it represents the
sequence of characters currently contained in the character array argument. |
String(char[] value, int offset,
int count) |
Allocates a new String that contains characters from a
subarray of the character array argument. |
String(int[] codePoints, int offset,
int count) |
Allocates a new String that contains characters from a
subarray of the Unicode code point array argument. |
Initializes a newly created String object so that it
represents the same sequence of characters as the argument; in other words,
the newly created string is a copy of the argument string. |
Methods in class String
Method |
Description |
Returns true if and only if this string contains the
specified sequence of char values. |
|
Compares this string to the specified CharSequence. |
|
Compares this string to the specified StringBuffer. |
|
copyValueOf(char[] data) |
Returns a String that represents the character
sequence in the array specified. |
copyValueOf(char[] data, int offset, int count) |
Returns a String that represents the character
sequence in the array specified. |
Tests if this string ends with the specified suffix. |
|
Compares this string to the specified object. |
|
equalsIgnoreCase(String anotherString) |
Compares this String to
another String, ignoring case considerations. |
Returns a formatted string using the specified
locale, format string, and arguments. |
|
Returns a formatted string using the specified
format string and arguments. |
|
getBytes() |
Encodes this String into a sequence of
bytes using the platform's default charset, storing the result into a new
byte array. |
Encodes this String into a sequence of
bytes using the given charset, storing the result into a new byte array. |
getBytes(int srcBegin,
int srcEnd, byte[] dst, int dstBegin)Deprecated. |
This method does not properly convert characters
into bytes. As of JDK 1.1, the preferred way to do this is via the getBytes() method, which uses the platform's default
charset. |
getChars(int srcBegin,
int srcEnd, char[] dst, int dstBegin) |
Copies characters from this string into the
destination character array. |
hashCode() |
Returns a hash code for this string. |
indexOf(int ch) |
Returns the index within this string of the first
occurrence of the specified character. |
indexOf(int ch,
int fromIndex) |
Returns the index within this string of the first
occurrence of the specified character, starting the search at the specified
index. |
Returns the index within this string of the first
occurrence of the specified substring. |
|
Returns the index within this string of the first
occurrence of the specified substring, starting at the specified index. |
|
intern() |
Returns a canonical representation for the string
object. |
isEmpty() |
Returns true if, and only if, length() is 0. |
lastIndexOf(int ch) |
Returns the index within this string of the last
occurrence of the specified character. |
lastIndexOf(int ch,
int fromIndex) |
Returns the index within this string of the last
occurrence of the specified character, searching backward starting at the
specified index. |
lastIndexOf(String str) |
Returns the index within this string of the last
occurrence of the specified substring. |
lastIndexOf(String str,
int fromIndex) |
Returns the index within this string of the last
occurrence of the specified substring, searching backward starting at the
specified index. |
length() |
Returns the length of this string. |
Tells whether or not this string matches the
given regular expression. |
|
offsetByCodePoints(int index,
int codePointOffset) |
Returns the index within this String that is
offset from the given index by codePointOffset code
points. |
regionMatches(boolean ignoreCase,
int toffset, String other,
int ooffset, int len) |
Tests if two string regions are equal. |
regionMatches(int toffset, String other,
int ooffset, int len) |
Tests if two string regions are equal. |
replace(char oldChar, char newChar) |
Returns a new string resulting from replacing all
occurrences of oldChar in this string with newChar. |
replace(CharSequence target, CharSequence replacement) |
Replaces each substring of this string that matches
the literal target sequence with the specified literal replacement sequence. |
replaceAll(String regex, String replacement) |
Replaces each substring of this string that matches
the given regular expression with the given replacement. |
replaceFirst(String regex, String replacement) |
Replaces the first substring of this string that
matches the given regular expression with the given replacement. |
Splits this string around matches of the given regular expression. |
|
Splits this string around matches of the given regular expression. |
|
startsWith(String prefix) |
Tests if this string starts with the specified
prefix. |
startsWith(String prefix,
int toffset) |
Tests if the substring of this string beginning at
the specified index starts with the specified prefix. |
subSequence(int beginIndex,
int endIndex) |
Returns a new character sequence that is a
subsequence of this sequence. |
substring(int beginIndex) |
Returns a new string that is a substring of this
string. |
substring(int beginIndex,
int endIndex) |
Returns a new string that is a substring of this
string. |
Converts this string to a new character array. |
|
Converts all of the characters in
this String to lower case using the rules of the default locale. |
|
toLowerCase(Locale locale) |
Converts all of the characters in
this String to lower case using the rules of the given Locale. |
toString() |
This object (which is already a string!) is itself returned. |
Converts all of the characters in
this String to upper case using the rules of the default locale. |
|
toUpperCase(Locale locale) |
Converts all of the characters in
this String to upper case using the rules of the given Locale. |
trim() |
Returns a copy of the string, with leading and
trailing whitespace omitted. |
Example 15.5: Extracting substring of
a string
The
following program uses substring( ) to replace all instances of one
substring with another within a string:
// Substring replacement.
class StringReplace {
public static void main(String args[]) {
String org = "This is
a test. This is, too.";
String search =
"is";
String sub =
"was";
String result =
"";
int i;
do { // replace all
matching substrings
System.out.println(org);
i = org.indexOf(search);
if(i != -1) {
result = org.substring(0,
i);
result = result + sub;
result = result +
org.substring(i + search.length());
org = result;
}
} while(i != -1);
}
}
Example
15.6: Merging two strings
You can concatenate two strings
using concat( ). This method creates a new object
that contains the invoking string with the contents of str appended to the end. concat( ) performs
the same function as +. For example,
// String concatenation (merging).
class StringMergingDemo {
public static void main(String args[]) {
String s1 = "Debasis";
String s2 =
s1.concat("Samanta");
System.out.println(s1);
System.out.println();
System.out.println(s2);
//
Alternatively, + performs the same, for example
String s1 =
"Debasis";
String s2 = s1 +
"Samanta";
System.out.println(s1);
System.out.println();
System.out.println(s2);
}
}
Example 15.7: Replace character(s) in
a string by another character(s)
Thee is the
replace( ) method which has two
forms to this task. The first replaces all occurrences of one character in the invoking string with another
character. The second replaces a sequence of characters with another sequence
of characterts.
// Replacing characters in a
string.
class StringReplaceDemo {
public static void main(String args[]) {
String s1 =
"Java";
String s2 = s1.replace(‘a’,
‘u’); // Replace all occurrences of ‘a’ with ‘u’
System.out.println(s2);
System.out.println();
String s3 = "top and
pop";
String s4 = s.replace(“op”,
“oop”); // Replace “op” with “oop”
System.out.println(s4);
}
}
Example
15..8: Removing leading and railing whitespaces in a string
// Using trim() and equals() to process commands.
import java.io.*;
class StringTrimDemo {
public static void main(String args[]) throws
IOException. {
// create a BufferedReader
using System.in
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String str;
System.out.println("Enter
'stop' to quit.");
System.out.println("Enter
country: ");
do {
str = br.readLine();
str = str.trim(); // Remove
whitespace
if(str.equals("India"))
System.out.println("Capital
is New Delhi.");
else if(str.equals("America"))
System.out.println("Capital
is New York");
else if(str.equals("England"))
System.out.println("Capital
is London");
else if(str.equals("Singapore"))
System.out.println("Capital is Singapore!");
}
while(!str.equals("stop
}
}
Example 15..9: Changing
the case of characters within a string
// Demonstrate toUpperCase() and toLowerCase().
class ChangeCaseDemo {
public static void main(String args[]) {
String s = "This is a
test.";
System.out.println("Original:
" + s);
String upper = s.toUpperCase();
String lower = s.toLowerCase();
System.out.println("Uppercase:
" + upper);
System.out.println("Lowercase:
" + lower);
}
}
Example 15.10: Joining strings
with delimiter
JDK 8 adds a new method to String called join( ). It is used to concatenate two or
more strings, separating each string with a delimiter, such as a space or a
comma. The following program
demonstrates this version of join(
):
// Demonstrate the join() method defined by String.
class StringJoinDemo {
public static void main(String args[]) {
String result =
String.join(" ", "Alpha", "Beta",
"Gamma");
System.out.println(result);
result = String.join(", ", "Java",
"query","E-mail: java@google.com");
System.out.println(result);
}
}
StringBuffer Class
The major limitation with String objects
is that they are immutable, that is, once you create an object, it cannot be
modified; for example, cannot insert, delete and append a character into it. On
the other hand, an object of the class StringBuffer is like a String, but can
be modified. At any point in time, a
StringBuffer object contains some particular sequence of characters, but the
length and content of the sequence can be changed through certain method calls.
Further, a StringBuffer object is thread-safe. The major difference between the
two classes are summarized in the table given below.
String |
StringBuffer |
String class is immutable. |
StringBuffer class is mutable. |
String is slow and consumes more
memory when you concat too many strings because every time it creates new instance. |
StringBuffer is fast and consumes less
memory when you cancat strings. |
String class overrides the equals()
method of Object class. So you can compare the contents of two
strings by equals() method. |
StringBuffer class doesn't override
the equals() method of Object class. |
Modifying a String
Because String objects are immutable, whenever you want to
modify a String, you must either copy it into a StringBuffer or StringBuilder,
or use a String method that constructs a new copy of the string with
your modifications complete. A sampling of these methods are described here.
Class StringBuffer
StringBuffer supports
a modifiable string. As you know, String represents fixed-length, immutable
character sequences. In contrast, StringBuffer represents growable and
writable character sequences. StringBuffer may have characters and
substrings inserted in the middle or appended to the end. StringBuffer will
automatically grow to make room for such additions and often has more
characters preallocated than are actually needed, to allow room for growth.
StringBuffer constructors
StringBuffer defines these
four constructors:
Constructor |
Description |
StringBuffer() |
Constructs a string buffer with no characters in it
and an initial capacity of 16 characters. |
StringBuffer(CharSequence seq) |
Constructs a string buffer that contains the same
characters as the specified CharSequence. |
StringBuffer(int capacity) |
Constructs a string buffer with no characters in it
and the specified initial capacity. |
StringBuffer(String str) |
Constructs a string buffer initialized to the
contents of the specified string. |
The default constructor (the one with no parameters) reserves room
for 16 characters without reallocation. The second version accepts an integer
argument that explicitly sets the size of the buffer. The third version accepts
a String argument that sets the initial contents of the StringBuffer object
and reserves room for 16 more characters without reallocation. StringBuffer allocates
room for 16 additional characters when no specific buffer length is requested,
because reallocation is a costly process in terms of time. Also, frequent
reallocations can fragment memory. By allocating room for a few extra
characters, StringBuffer reduces the number of reallocations that take
place. The fourth constructor creates an object that contains the character
sequence contained in chars and reserves room for 16 more characters.
StringBuffer methods
Method |
Description |
append(boolean b) |
Appends the string representation of
the boolean argument to the sequence. |
append(char c) |
Appends the string representation of
the char argument to this sequence. |
append(char[] str) |
Appends the string representation of
the char array argument to this sequence. |
append(char[] str, int offset, int len) |
Appends the string representation of a
subarray of the char array argument to this sequence. |
Appends the
specified CharSequence to this sequence. |
|
append(CharSequence s, int start, int end) |
Appends a subsequence of the
specified CharSequence to this sequence. |
append(double d) |
Appends the string representation of the double argument
to this sequence. |
append(float f) |
Appends the string representation of
the float argument to this sequence. |
append(int i) |
Appends the string representation of
the int argument to this sequence. |
append(long lng) |
Appends the string representation of
the long argument to this sequence. |
Appends the string representation of
the Object argument. |
|
Appends the specified string to this
character sequence. |
|
append(StringBuffer sb) |
Appends the specified StringBuffer to
this sequence. |
appendCodePoint(int codePoint) |
Appends the string representation of
the codePoint argument to this sequence. |
capacity() |
Returns the current capacity. |
Attempts to reduce storage used for the
character sequence. |
|
charAt(int index) |
Returns the char value in this
sequence at the specified index. |
codePointAt(int index) |
Returns the character (Unicode code
point) at the specified index. |
codePointBefore(int index) |
Returns the character (Unicode code
point) before the specified index. |
codePointCount(int beginIndex,
int endIndex) |
Returns the number of Unicode code
points in the specified text range of this sequence. |
delete(int start,
int end) |
Removes the characters in a substring of
this sequence. |
deleteCharAt(int index) |
Removes the char at the
specified position in this sequence. |
ensureCapacity(int minimumCapacity) |
Ensures that the capacity is at least
equal to the specified minimum. |
getChars(int srcBegin,
int srcEnd, char[] dst, int dstBegin) |
Characters are copied from this sequence
into the destination character array dst. |
toString() |
Returns a string representing the data
in this sequence. |
Returns the index within this string of
the first occurrence of the specified substring. |
|
Returns the index within this string of
the first occurrence of the specified substring, starting at the specified
index. |
|
insert(int offset,
boolean b) |
Inserts the string representation of
the boolean argument into this sequence. |
insert(int offset,
char c) |
Inserts the string representation of
the char argument into this sequence. |
insert(int offset,
char[] str) |
Inserts the string representation of
the char array argument into this sequence. |
insert(int index,
char[] str, int offset, int len) |
Inserts the string representation of a
subarray of the str array argument into this sequence. |
insert(int dstOffset, CharSequence s) |
Inserts the
specified CharSequence into this sequence. |
insert(int dstOffset, CharSequence s, int start,
int end) |
Inserts a subsequence of the
specified CharSequence into this sequence. |
insert(int offset,
double d) |
Inserts the string representation of
the double argument into this sequence. |
insert(int offset, float f) |
Inserts the string representation of
the float argument into this sequence. |
insert(int offset,
long l) |
Inserts the string representation of
the long argument into this sequence. |
Inserts the string representation of the Object argument
into this character sequence. |
|
Inserts the string into this character
sequence. |
|
lastIndexOf(String str) |
Returns the index within this string of
the rightmost occurrence of the specified substring. |
lastIndexOf(String str,
int fromIndex) |
Returns the index within this string of
the last occurrence of the specified substring. |
length() |
Returns the length (character count). |
offsetByCodePoints(int index,
int codePointOffset) |
Returns the index within this sequence
that is offset from the
given index by codePointOffset code points. |
Replaces the characters in a substring
of this sequence with characters in the specified String. |
|
reverse() |
Causes this character sequence to be
replaced by the reverse of the sequence. |
setCharAt(int index,
char ch) |
The character at the specified index is
set to ch. |
setLength(int newLength) |
Sets the length of the character
sequence. |
subSequence(int start,
int end) |
Returns a new character sequence that is
a subsequence of this sequence. |
substring(int start) |
Returns a new String that
contains a subsequence of characters currently contained in this character
sequence. |
substring(int start,
int end) |
Returns a new String that
contains a subsequence of characters currently contained in this sequence. |
Example 15.11: Length and
capacity of a string
// StringBuffer length vs. capacity.
class StringBufferDemo {
public static void main(String args[]) {
StringBuffer sb = new
StringBuffer("Hello");
System.out.println("String
= " + sb);
System.out.println("Length
= " + sb.length());
System.out.println("Capacity
= " + sb.capacity());
}
}
Here is the output of this
program:
String = Hello
length = 5
capacity = 21
Note:
Since sb is
initialized with the string "Hello" when it is created, its length is
5. Its capacity is 21 because room for 16 additional characters is
automatically added.
Example 15.12: Modifying a string
The following example
demonstrates charAt(
) and setCharAt( ) to modify a string object:
// Demonstrate charAt() and setCharAt().
class setCharAtDemo {
public static void main(String args[]) {
StringBuffer sb = new
StringBuffer("Hello");
System.out.println("Suffer
before = " + sb);
System.out.println("charAt(1)
before = " + sb.charAt(1));
sb.setCharAt(1, 'i');
sb.setLength(2);
System.out.println("buffer
after = " + sb);
System.out.println("charAt(1)
after = " + sb.charAt(1));
}
}
Here is the output generated by
this program:
Suffer before = Hello
charAt(1) before = e
String after = Hi
charAt(1) after = i
Example 15.13: Merging strings of StringBuffer
The append( ) method concatenates the string representation
of any other type of data to the end of the invoking StringBuffer object.
It has several overloaded versions. Here are a few of its forms:
StringBuffer
append(String str)
StringBuffer
append(int num)
StringBuffer
append(Object obj)
The
string representation of each parameter is obtained, often by calling String.valueOf(
). The result is appended to the current StringBuffer object. The
buffer itself is returned by each version of append( ). This allows
subsequent calls to be chained together, as shown in the following example:
// Demonstrate append().
class AppendDemo {
public
static void main(String args[]) {
String
s;
int
a = 42;
StringBuffer
sb = new StringBuffer(40);
s
= sb.append("a =").append(a).append("!").toString();
System.out.println(s);
}
}
The output of this example is
shown here:
a = 42!
Example 15.14: Merging strings of String and StringBuffer
Following example illustrates how
StringBuffer is faster than the String class with reference to the concatenate
operation.
public class
ConcatTest{
public static String
concatWithString() {
String t = "Java";
for (int i=0; i<10000; i++){
t = t + "Tpoint";
}
return t;
}
public static String
concatWithStringBuffer(){
StringBuffer sb = new
StringBuffer("Java");
for (int i=0; i<10000; i++){
sb.append("Tpoint");
}
return sb.toString();
}
public static void main(String[]
args){
long startTime =
System.currentTimeMillis();
concatWithString();
System.out.println("Time taken by
Concating with String:
"+(System.currentTimeMillis()-startTime)+"ms");
startTime = System.currentTimeMillis();
concatWithStringBuffer();
System.out.println("Time taken by
Concating with StringBuffer:
"+(System.currentTimeMillis()-startTime)+"ms");
}
}
Example
15.15: Insert character to a string
The insert( ) method inserts one string into another. It is
overloaded to accept values of all the primitive types, plus Strings, Objects,
and CharSequences. Like append( ), it obtains the string
representation of the value it is called with. This string is then inserted
into the invoking StringBuffer object. These are a few of its forms:
StringBuffer
insert(int index, String str)
StringBuffer
insert(int index, char ch)
StringBuffer
insert(int index, Object obj)
Here, index specifies
the index at which point the string will be inserted into the invoking StringBuffer object.
The following sample program
inserts "like" between "I" and "Java":
// Demonstrate insert().
class insertDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("I Java!");
sb.insert(2, "like
");
System.out.println(sb);
}
}
Example
15.16: Reversing a string
You can reverse the characters
within a StringBuffer object using reverse( ), shown here: This method returns the reverse of the object on which
it was called. The following
program demonstrates reverse( ).
// Using reverse() to reverse a StringBuffer.
class StringReverseDemo {
public static void main(String args[]) {
StringBuffer s = new
StringBuffer("abcdef");
System.out.println(s);
s.reverse();
System.out.println(s);
}
}
Example
15.17: String modification
Here
is a program that demonstrates the delete( ) and deleteCharAt( ) methods:
// Demonstrate delete() and deleteCharAt()
class StringDeleteDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("This is a test.");
sb.delete(4, 7);
System.out.println("After
delete: " + sb);
sb.deleteCharAt(0);
System.out.println("After
deleteCharAt: " + sb);
}
}
The following output is produced:
After delete: This a test.
After deleteCharAt: his a test.
Example
15.18: Replacing a string
You can replace one set of characters with another set inside a StringBuffer
object by calling replace( ). The following program demonstrates replace(
):
// Demonstrate replace()
class replaceDemo {
public static void main(String args[]) {
StringBuffer sb = new
StringBuffer("This is a test.");
sb.replace(5, 7,
"was");
System.out.println("After
replace: " + sb);
}
}
Here is the output:
After replace: This was a test.
Example
15.19: Substring of a string
You
can obtain a portion of a StringBuffer by calling substring( ).
It has the following two forms:
String
substring(int startIndex)
String
substring(int startIndex, int endIndex)
The first form returns the substring that starts at startIndex and
runs to the end of the invoking StringBuffer object. The second form
returns the substring that starts at startIndex and runs through endIndex–1.
These methods work just like those defined for String that were
described earlier. The following program demonstrates indexOf( ) and lastIndexOf(
):
class IndexOfDemo
{
public static void main(String args[]) {
StringBuffer sb = new
StringBuffer("one two one");
int i;
i =
sb.indexOf("one");
System.out.println("First
index: " + i);
i =
sb.lastIndexOf("one");
System.out.println("Last
index: " + i);
}
}
Example
15.20: hashCode( ) of a string
public class InstanceTest{
public static void main(String args[]){
System.out.println("Hashcode test of String:");
String str="java";
System.out.println(str.hashCode());
str=str+"tpoint";
System.out.println(str.hashCode());
System.out.println("Hashcode test of StringBuffer:");
StringBuffer sb=new StringBuffer("java");
System.out.println(sb.hashCode());
sb.append("tpoint");
System.out.println(sb.hashCode());
}
}
Example
15.21: String to other forms
Methods
toBinaryString( ), toHexString( ), and toOctalString( ),
which convert a value into a binary, hexadecimal, or octal string,
respectively. The following program demonstrates binary, hexadecimal, and octal
conversion:
// Convert an integer into binary, hexadecimal, and octal.
class StringConversions {
public static void main(String args[]) {
int num = 19648;
System.out.println(num +
" in binary: " +
Integer.toBinaryString(num));
System.out.println(num +
" in octal: " +
Integer.toOctalString(num));
System.out.println(num +
" in hexadecimal: " +
Integer.toHexString(num));
}
}
The output of this program is
shown here:
19648 in binary: 100110011000000
19648 in octal: 46300
19648 in hexadecimal: 4cc0
StringBuilder
Introduced by JDK 5, StringBuilder is a relatively recent
addition to Java’s string handling capabilities. StringBuilder is
similar to StringBuffer except for one important difference: it is not
synchronized, which means that it is not thread-safe. The advantage of StringBuilder
is faster performance. However, in cases in which a mutable string will be
accessed by multiple threads, and no external synchronization is employed, you
must use StringBuffer rather than StringBuilder.
StringTokenizer
•
The processing of text often
consists of parsing a formatted input string. Parsing is the division of
text into a set of discrete parts, or tokens, which in a certain
sequence can convey a semantic meaning.
•
The StringTokenizer class
provides the first step in this parsing process, often called the lexer (lexical
analyzer) or scanner.
•
StringTokenizer implements
the Enumeration interface.
•
Therefore, given an input string,
you can enumerate the individual tokens contained in it using StringTokenizer.
The StringTokenizer constructors are shown here:
Method |
Description |
StringTokenizer(String str) |
Constructs a
string tokenizer for the specified string. |
StringTokenizer(String str, String delim) |
Constructs a
string tokenizer for the specified string. |
StringTokenizer(String str, String delim, boolean returnDelims) |
Constructs a
string tokenizer for the specified string. |
The StringTokenizer methods are shown here:
Method |
Description |
Calculates
the number of times that this tokenizer's nextToken method can be called
before it generates an exception. |
|
Returns the
same value as the hasMoreTokens method. |
|
Tests if
there are more tokens available from this tokenizer's string. |
|
Returns the
same value as the nextToken method, except that its declared return
value is Object rather than String. |
|
Returns the
next token from this string tokenizer. |
|
Returns the
next token in this string tokenizer's string. |
In all versions, str is the string that will be tokenized.
In the first version, the default delimiters are used. In the second and third
versions, delimiters is a string that specifies the delimiters. In the
third version, if delimAsToken is true, then the delimiters are
also returned as tokens when the string is parsed. Otherwise, the delimiters
are not returned. Delimiters are not returned as tokens by the first two forms.
Once you have created a StringTokenizer object, the nextToken(
) method is used to extract consecutive tokens. The hasMoreTokens( ) method
returns true while there are more tokens to be extracted. Since StringTokenizer
implements Enumeration, the hasMoreElements( ) and nextElement(
) methods are also implemented, and they act the same as hasMoreTokens(
) and nextToken( ), respectively.
Example
15.22: String to other forms
Here is an example that creates a StringTokenizer to parse
"key=value" pairs. Consecutive sets of "key=value" pairs
are separated by a semicolon.
// Demonstrate
StringTokenizer.
import java.util.StringTokenizer;
class StringTokenizerDemo{
static String in = "Title=Data Structures Using Java;" +
"Author=Debasis
Samanta;" + "Publisher=NPTEL;" + "Copyright=2020";
public static void main(String args[]) {
StringTokenizer st = new
StringTokenizer(in, "=;");
while(st.hasMoreTokens()) {
String key = st.nextToken();
String val = st.nextToken();
System.out.println(key + "\t" + val);
}
}
}
The output from this program is
shown here:
Title Data Structures Using Java
Author Debasis Samanta
Publisher NPTEL
Copyright 2020
Miscellaneous Utilities
Date
The Date class encapsulates the current date and time. When Java 1.1 was released, many of the
functions carried out by the original Date class were moved into the Calendar
and DateFormat classes, and as a result, many of the original 1.0 Date
methods were deprecated.
Constructors defined by class Date
Constructor |
Description |
Date() |
Creates date object representing current date
and time. |
Date(long date) |
Allocates
a Date object and initializes it to represent the specified number
of milliseconds since the standard base time known as "the epoch",
namely January 1, 1970, 00:00:00 GMT. |
Date(int year, int month, int date) |
Create
a date with the specific data as yyyy/mm/dd. |
Date(int year, int month, int date, int hrs, int min) |
Create a date with the specific data with time. |
Date(int year, int month, int date, int hrs, int min, int sec) |
Create a date with the specific data with detailed time. |
Date(String s) |
Create
a date with the specific data as a string. |
The first constructor initializes the object with the current date
and time. The second constructor accepts one argument that equals the number of
milliseconds that have elapsed since midnight, January 1, 1970. The last four
constructors are currently being deprecated.
Example 17.1:
Creating objects of Date class
The following program demonstrates, how to obtain the date and
time in terms of milliseconds, in its default string representation as returned
by toString( ), or (beginning with JDK 8) as an Instant object.
To obtain more-detailed information about the date and time, you will use the Calendar
class.
// Show date
and time using only Date methods.
import java.util.Date;
class CreateDateDemo {
public static void main(String args[]) {
// Creating an instantiate a Date object
Date
date1 = new Date(); //
Create an object of the current date
// Display time and date using toString()
System.out.println(“Current date: “
+ date1);
Date date2 = new
Date(2323223232L);
System.out.println("Your
date is: "+ date2 );
// Create a date object with specific data
Date date3 = new
Date(1965,
1, 12);
System.out.println("Another date is:
"+ date3 );
}
}
Sample
output is shown here:
Current date: Sun Mar 01 08:13:24 CST 2020
Your date is: Wed Jan 28 02:50:23 IST 1970
Another date is: Mon Jan 12 00:00:00 IST 1964
Methods defined by class Date
The nondeprecated methods defined by Date are shown in
Table below. Date also implements the Comparable interface. The
table lists only the non-deprecated methods.
Method |
Description |
Tests
if this date is after the specified date. |
|
Tests
if this date is before the specified date. |
|
clone() |
Return
a copy of this object. |
Compares
two Dates for ordering. |
|
Compares
two dates for equality. |
|
Obtains
an instance of Date from an Instant object. |
|
getTime() |
Returns
the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by
this Date object. |
hashCode() |
Returns
a hash code value for this object. |
setTime(long time) |
Sets
this Date object to represent a point in time that
is time milliseconds after January 1, 1970 00:00:00 GMT. |
Converts
this Date object to an Instant. |
|
toString() |
Converts
this Date object to a String form. |
Example 17.2:
Simple examples of date objects
The following program demonstrates, how to obtain the date and
time in terms of milliseconds, in its default string representation as returned
by toString( ), or (beginning with JDK 8) as an Instant object.
To obtain more-detailed information about the date and time, you will use the Calendar
class.
// Show date
and time using only Date methods.
import java.util.Date;
class UseDateDemo {
public static void main(String args[]) {
// Creating date objects
Date
d1 = new
Date(2000,
11, 21);
Date
d2 = new
Date();
// Current date
Date
d3 = new
Date(2010, 1,
3);
boolean
a = d3.after(d1);
System.out.println("Date
d3 comes after "
+
"date
d2: "
+ a);
boolean
b = d3.before(d2);
System.out.println("Date
d3 comes before "+
"date
d2: "
+ b);
int
c = d1.compareTo(d2);
System.out.println(c);
//
Display number of milliseconds since midnight, January 1, 1970 GMT
System.out.println("Miliseconds
from Jan 1 "+
"1970
to date d1 is "
+ d1.getTime());
System.out.println("Before
setting "+d2.toString());
d2.setTime(204587433443L);
System.out.println("After
setting "+d2.toString());
}
}
Sample
output is shown here:
Date d3 comes after date d2: true
Date d3 comes before date d2: false
1
Miliseconds from Jan 1 1970 to date d1 is
60935500800000
Before setting Tue Jul 12 13:13:16 UTC 2016
After setting Fri Jun 25 21:50:33 UTC 1976
Example 17.3:
Another example of date class
import
java.util.*;
public
class DateChangeDemo {
public static void main(String args[]) {
try
{
System.out.println(new Date( ) +
"\n");
Thread.sleep(5*60*10);
System.out.println(new Date( ) +
"\n");
} catch (Exception e) {
System.out.println("Got an
exception!");
}
}
}
Sample
output is shown here:
Fri Apr 10 18:04:41
GMT 2020
Fri Apr 10 18:04:51
GMT 2020
Example 17.4:
Measuring elapsed time between two dates
import
java.util.*;
public
class ElapsedTimeDemo {
public static void main(String args[]) {
try {
long start = System.currentTimeMillis(
);
System.out.println(new Date( ) +
"\n");
Thread.sleep(5*60*10);
System.out.println(new Date( ) +
"\n");
long end = System.currentTimeMillis(
);
long diff = end - start;
System.out.println("Difference is
: " + diff);
} catch (Exception e) {
System.out.println("Got an
exception!");
}
}
}
Sample
output is shown here:
Fri Apr 10
18:16:51 GMT 2020
Fri Apr 10
18:16:57 GMT 2020
Difference is :
5993
Calendar
The abstract Calendar class provides a set
of methods that allows you to convert a time in milliseconds to a number of
useful components. The type of information that can be provided are:
• Year
• Month
• Day
• Hour
• Minute
• Second
It is intended that subclasses of Calendar will
provide the specific functionality to interpret time information according to
their own rules. An example of such a subclass is GregorianCalendar.
Note: JDK 8 defines a new date and time API in java.time, which new
applications may want to employ.
Constructors defined by class Calendar
Calendar provides
no public constructors.
Methods defined by class Calendar
A sampling of methods defined by Calendar are shown in table
below.
|
Method |
Description |
|
|
add(int field, int amount) |
Adds
or subtracts the specified amount of time to the given calendar field, based
on the calendar's rules. |
|
|
Returns
whether this Calendar represents a time after the time represented
by the specified Object. |
||
|
Returns
whether this Calendar represents a time before the time represented
by the specified Object. |
||
|
clear() |
Sets
all the calendar field values and the time value (millisecond offset from
the Epoch)
of this Calendar undefined. |
|
|
clear(int field) |
Sets
the given calendar field value and the time value (millisecond offset from
the Epoch)
of this Calendar undefined. |
|
|
clone() |
Creates
and returns a copy of this object. |
|
|
Compares
the time values (millisecond offsets from the Epoch)
represented by two Calendar objects. |
||
|
complete() |
Fills
in any unset fields in the calendar fields. |
|
|
Converts
the current millisecond time value time to
calendar field values in fields[]. |
||
Converts
the current calendar field values in fields[] to
the millisecond time value time. |
|||
Compares
this Calendar to the specified Object. |
|||
get(int field) |
Returns the value of the given
calendar field. |
||
getActualMaximum(int field) |
Returns the maximum value that
the specified calendar field could have, given the time value of
this Calendar. |
||
getActualMinimum(int field) |
Returns the minimum value that
the specified calendar field could have, given the time value of
this Calendar. |
||
Returns an array of all locales
for which the getInstance methods of this class can return
localized instances. |
|||
getDisplayName(int field,
int style, Locale locale) |
Returns the string
representation of the calendar field value in the
given style and locale. |
||
getDisplayNames(int field,
int style, Locale locale) |
Returns
a Map containing all names of the calendar field in the
given style and locale and their corresponding field
values. |
||
Gets what the first day of the
week is; e.g., SUNDAY in the U.S., MONDAY in France. |
|||
getGreatestMinimum(int field) |
Returns the highest minimum
value for the given calendar field of this Calendar instance. |
||
Gets a calendar using the
default time zone and locale. |
|||
getInstance(Locale aLocale) |
Gets a calendar using the
default time zone and specified locale. |
||
getInstance(TimeZone zone) |
Gets a calendar using the
specified time zone and default locale. |
||
getInstance(TimeZone zone, Locale aLocale) |
Gets a calendar with the
specified time zone and locale. |
||
getLeastMaximum(int field) |
Returns the lowest maximum
value for the given calendar field of this Calendar instance. |
||
getMaximum(int field) |
Returns the maximum value for
the given calendar field of this Calendar instance. |
||
Gets what the minimal days
required in the first week of the year are; |
|||
getMinimum(int field) |
Returns the minimum value for
the given calendar field of this Calendar instance. |
||
getTime() |
Returns a Date object
representing this Calendar's time value (millisecond offset from
the Epoch"). |
||
Returns this Calendar's time
value in milliseconds. |
|||
setWeekDate(int weekYear,
int weekOfYear, int dayOfWeek) |
Sets the date of
this Calendar with the the given date specifiers - week year, week
of year, and day of week. |
||
Gets the time zone. |
|||
Returns the number of weeks in
the week year represented by this Calendar. |
|||
Returns the week year
represented by this Calendar. |
|||
hashCode() |
Returns a hash code for this
calendar. |
||
internalGet(int field) |
Returns the value of the given
calendar field. |
||
Tells whether date/time
interpretation is to be lenient. |
|||
isSet(int field) |
Determines if the given
calendar field has a value set, including cases that the value has been set
by internal fields calculations triggered by a get method call. |
||
Returns whether this Calendar supports week dates. |
|||
roll(int field,
boolean up) |
Adds or subtracts (up/down) a single unit of time on the given
time field without changing larger fields. |
||
roll(int field,
int amount) |
Adds the specified (signed) amount to the specified calendar
field without changing larger fields. |
||
toString() |
Return a string representation of this calendar. |
||
set(int field,
int value) |
Sets the given calendar field to the given value. |
||
set(int year,
int month, int date) |
Sets the values for the calendar fields YEAR, MONTH,
and DAY_OF_MONTH. |
||
set(int year,
int month, int date, int hourOfDay, int minute) |
Sets the values for the calendar
fields YEAR, MONTH, DAY_OF_MONTH, HOUR_OF_DAY,
and MINUTE. |
||
set(int year,
int month, int date, int hourOfDay, int minute,
int second) |
Sets the values for the
fields YEAR, MONTH, DAY_OF_MONTH, HOUR, MINUTE,
and SECOND. |
||
setFirstDayOfWeek(int value) |
Sets what the first day of the week is;
e.g., SUNDAY in the U.S., MONDAY in France. |
||
setLenient(boolean lenient) |
Specifies whether or not date/time interpretation is to be
lenient. |
||
setMinimalDaysInFirstWeek(int value) |
Sets what the minimal days required in the first week of the
year are; |
||
Sets this Calendar's time with the given Date. |
|||
setTimeInMillis(long millis) |
Sets this Calendar's current time from the given long value. |
||
setTimeZone(TimeZone value) |
Sets the time zone with the given time zone value. |
||
Fields defined by class Calendar
Calendar defines
the following int constants, which are used when you get or set
components of the calendar. (The ones with the suffix FORMAT or STANDALONE
were added by JDK 8.)
Note:
areFieldsSet is a boolean
that indicates if the time components have been set. fields is an
array of ints that holds the components of the time. isSet is a boolean
array that indicates if a specific time component has been set. time is
a long that holds the current time for this object. isTimeSet is
a boolean that indicates if the current time has been set.
Example 17.5:
Illustration of calendar objects
The following program demonstrates several Calendar methods:
import java.util.Calendar;
class CalendarDemo {
public static void main(String args[]) {
// Set months in your
calendar
String months[] = {"Jan", "Feb", "Mar", "Apr","May", "Jun", "Jul", "Aug",
"Sep", "Oct", "Nov", "Dec"};
/* Get an instance of a calendar
initialized with the current date and time in the default locale and time zone.
*/
Calendar calendar = Calendar.getInstance();
// Display current time and date information.
System.out.print("Date: ");
System.out.print(months[calendar.get(Calendar.MONTH)]);
System.out.print(" " + calendar.get(Calendar.DATE) + " ");
System.out.println(calendar.get(Calendar.YEAR));
System.out.print("Time: ");
System.out.print(calendar.get(Calendar.HOUR) + ":");
System.out.print(calendar.get(Calendar.MINUTE) + ":");
System.out.println(calendar.get(Calendar.SECOND));
// Set the time and date information and display it.
calendar.set(Calendar.HOUR, 10);
calendar.set(Calendar.MINUTE, 29);
calendar.set(Calendar.SECOND, 22);
System.out.print("Updated time: ");
System.out.print(calendar.get(Calendar.HOUR) + ":");
System.out.print(calendar.get(Calendar.MINUTE) + ":");
System.out.println(calendar.get(Calendar.SECOND));
// Getting certain information about the
calendar object
int
max =
calendar.getMaximum(Calendar.DAY_OF_WEEK);
System.out.println("Maximum
number of days in a week: "
+ max);
max
= calendar.getMaximum(Calendar.WEEK_OF_YEAR);
System.out.println("Maximum
number of weeks in a year: "
+ max);
// Seeting for an updated in the instance of the calendar
calendar.add(Calendar.DATE,
-15);
System.out.println("15
days ago: "
+ calendar.getTime());
calendar.add(Calendar.MONTH,
4);
System.out.println("4
months later: "
+ calendar.getTime());
calendar.add(Calendar.YEAR,
2);
System.out.println("2
years later: "
+ calendar.getTime());
}
}
Sample
output is shown here:
Date: Jan 1 2014
Time: 11:29:39
Updated time: 10:29:22
Maximum number of days in a week: 7
Maximum number of weeks in a year: 53
15 days ago: Mon Aug 13 11:10:57 UTC 2018
4 months later: Thu Dec 13 11:10:57 UTC 2018
2 years later: Sun Dec 13 11:10:57 UTC 2020
GregorianCalendar
GregorianCalendar is a concrete implementation of a Calendar that
implements the normal Gregorian calendar with which you are familiar. The getInstance(
) method of Calendar will typically return a GregorianCalendar initialized
with the current date and time in the default locale and time zone. GregorianCalendar defines two fields: AD and BC. These
represent the two eras defined by the Gregorian calendar.
Constructors defined by class GregorianCalendar
There are also several constructors for GregorianCalendar objects.
The default, GregorianCalendar(), initializes the object with the
current date and time in the default locale and time zone. Three more
constructors offer increasing levels of specificity. All
three versions set the day, month, and year. Here, year specifies the
year. The month is specified by month, with zero indicating January. The
day of the month is specified by dayOfMonth. The first version sets the
time to midnight. The second version also sets the hours and the minutes. The
third version adds seconds.
Constructor |
Description |
Constructs
a default GregorianCalendar using the current time in the default
time zone with the default locale. |
|
GregorianCalendar(int year, int month,
int dayOfMonth) |
Constructs
a GregorianCalendar with the given date set in the default time
zone with the default locale. |
GregorianCalendar(int year, int month,
int dayOfMonth, int hourOfDay, int minute) |
Constructs
a GregorianCalendar with the given date and time set for the
default time zone with the default locale. |
GregorianCalendar(int year, int month,
int dayOfMonth, int hourOfDay, int minute, int second) |
Constructs
a GregorianCalendar with the given date and time set for the default time
zone with the default locale. |
GregorianCalendar(Locale aLocale) |
Constructs
a GregorianCalendar based on the current time in the default time
zone with the given locale. |
GregorianCalendar(TimeZone zone) |
Constructs
a GregorianCalendar based on the current time in the given time
zone with the default locale. |
GregorianCalendar(TimeZone zone, Locale aLocale) |
Constructs
a GregorianCalendar based on the current time in the given time
zone with the given locale. |
Methods defined by class GregorianCalendar
GregorianCalendar provides
an implementation of all the abstract methods in Calendar. It also
provides some additional methods. Perhaps the most interesting is isLeapYear(
), which tests if the year is a leap year. Its form is boolean
isLeapYear(int year) This method returns true if year is a
leap year and false otherwise. JDK 8 also adds the following methods: from(
) and toZonedDateTime( ), which support the new date and time API,
and getCalendarType( ), which returns the calendar type as a string,
which is “gregory”. The following program demonstrates GregorianCalendar:
Example 17.6:
Illustration of Gregorian calendar objects
// Demonstrate GregorianCalendar
import java.util.*;
class GregorianCalendarDemo {
public static void main(String args[]) {
String months[] = {"Jan", "Feb", "Mar", "Apr",
"May", "Jun", "Jul", "Aug",
"Sep", "Oct", "Nov", "Dec"};
int year;
/* Create a Gregorian calendar initialized with the current date
and time in the
default locale and timezone. */
GregorianCalendar
gcalendar = new GregorianCalendar();
// Display current time and date information.
System.out.print("Date: ");
System.out.print(months[gcalendar.get(Calendar.MONTH)]);
System.out.print(" " + gcalendar.get(Calendar.DATE) + " ");
System.out.println(year = gcalendar.get(Calendar.YEAR));
System.out.print("Time: ");
System.out.print(gcalendar.get(Calendar.HOUR) + ":");
System.out.print(gcalendar.get(Calendar.MINUTE) + ":");
System.out.println(gcalendar.get(Calendar.SECOND));
// Test if the current year is a leap year
if(gcalendar.isLeapYear(year)) {
System.out.println("The current year is a leap
year");
}
else {
System.out.println("The current year is not a leap
year");
}
}
}
Sample
output is shown here:
Date: Jan 1 2014
Time: 1:45:5
The current year is not a leap year
TimeZone
We divide the whole earth east to west into 24
different regions based on longitude so each region is 15 degrees wider. “Time
Zone” is used to describe the current time for different areas of the world. It
refers to one of the specific regions out of the 24 total regions in the world
that are divided up by longitude. So, there are 24 different Time zones
available on earth. Each time zone is 15 degrees wide and there’s a one-hour
difference between each one.
·
Within each one of those
regions, a standard version of time is maintained. The different time zones are
calculated based on their relation to the coordinated universal time or UTC
(also referred to as Greenwich Mean Time (GMT)).
The abstract TimeZone class allows you to
work with time zone offsets from Greenwich mean time (GMT).
The Java TimeZone class is a class that represents
time zones, and is helpful when doing calendar arithmetics across time zones.
The java.util.TimeZone class is used in conjunction with the java.util.Calendar class.
Constructors
TimeZone only supplies the default constructor.
A sampling of methods defined by TimeZone is given in the
following table.
Method |
Description |
clone() |
Creates
a copy of this TimeZone. |
Gets
all the available IDs supported. |
|
getAvailableIDs(int rawOffset) |
Gets
the available IDs according to the given time zone offset in milliseconds. |
Gets
the default TimeZone for this host. |
|
Returns
a long standard time name of this TimeZone suitable for
presentation to the user in the default locale. |
|
getDisplayName(boolean daylight, int style) |
Returns
a name in the specified style of this TimeZone suitable
for presentation to the user in the default locale. |
getDisplayName(boolean daylight, int style, Locale locale) |
Returns
a name in the specified style of this TimeZone suitable
for presentation to the user in the specified locale. |
getDisplayName(Locale locale) |
Returns
a long standard time name of this TimeZone suitable for
presentation to the user in the specified locale. |
Returns
the amount of time to be added to local standard time to get local wall clock
time. |
|
getID() |
Gets
the ID of this time zone. |
getOffset(int era,
int year, int month, int day, int dayOfWeek,
int milliseconds) |
Gets the time zone offset, for current date, modified in case of
daylight savings. |
getOffset(long date) |
Returns the offset of this time zone from UTC at the specified
date. |
Returns the amount of time in milliseconds to add to UTC to get
standard time in this time zone. |
|
getTimeZone(String ID) |
Gets the TimeZone for the given ID. |
hasSameRules(TimeZone other) |
Returns true if this zone has the same rule and offset as
another zone. |
inDaylightTime(Date date) |
Queries if the given date is in Daylight Saving Time
in this time zone. |
Returns true if this TimeZone is currently
in Daylight Saving Time |
|
setDefault(TimeZone zone) |
Sets the TimeZone that is returned by
the getDefault method. |
Sets the time zone ID. |
|
setRawOffset(int offsetMillis) |
Sets the base time zone offset to GMT. |
Queries if this TimeZone uses Daylight Saving Time. |
Example 17.7:
Illustration of time zone objects
import java.util.*;
public class TimeZoneExample {
public static void main( String args[] ){
String[] zoneIds = TimeZone.getAvailableIDs(); //
Ids of all time zones
System.out.println(“Total time zones on the
earth: “ + zoneIds.length);
// All the timezones whose
offset is 7200000 (i.e., 2 hours)
String[]
timezones = TimeZone.getAvailableIDs(7200000);
System.out.print("No
of Time Zone having time offset 2 hours");
System.out.println(timezones.length); // Print total
no of Timezones
System.out.println("In TimeZone class available Ids are: ");
for (int i=0; i<timezones.length; i++){
System.out.println(timezones[i]);
}
TimeZone zone = TimeZone.getTimeZone("Asia/Kolkata");
System.out.println("The Offset value of TimeZone: " +
zone.getOffset(Calendar.ZONE_OFFSET));
String name = zone.getDisplayName();
System.out.println("Name of the time zone: "+ name);
}
}
Sample
output is shown here:
Total time zones on the earth: 628
No of Time Zone having time offset 2 hours:
43
In
TimeZone class available Ids are:
Africa/Abidjan
Africa/Accra
Africa/Addis_Ababa
Africa/Algiers
Africa/Asmara
Africa/Asmera
Africa/Bamako
Africa/Bangui
Africa/Banjul
Africa/Bissau
...and
so on ....
The
Offset value of TimeZone: 19800000
Name of
the time zone: India Standard Time
SimpleTimeZone
The SimpleTimeZone class is a convenient subclass of TimeZone.
It implements TimeZone's abstract methods and allows you to work with
time zones for a Gregorian calendar. It also computes daylight saving time.
SimpleTimeZone defines
four constructors.
Constructor |
Description |
SimpleTimeZone(int rawOffset, String ID) |
Constructs a SimpleTimeZone with the given base time zone offset
from GMT and time zone ID with no daylight saving time schedule. |
SimpleTimeZone(int rawOffset, String ID, int startMonth, int startDay,
int startDayOfWeek, int startTime, int endMonth,
int endDay, int endDayOfWeek, int endTime) |
Constructs a SimpleTimeZone with the given base time zone offset
from GMT, time zone ID, and rules for starting and ending the daylight time. |
SimpleTimeZone(int rawOffset, String ID, int startMonth, int startDay,
int startDayOfWeek, int startTime, int endMonth,
int endDay, int endDayOfWeek, int endTime,
int dstSavings) |
Constructs a SimpleTimeZone with the given base time zone offset
from GMT, time zone ID, and rules for starting and ending the daylight time. |
SimpleTimeZone(int rawOffset, String ID, int startMonth, int startDay,
int startDayOfWeek, int startTime, int startTimeMode,
int endMonth, int endDay, int endDayOfWeek, int endTime,
int endTimeMode, int dstSavings) |
Constructs a SimpleTimeZone with the given base time zone offset
from GMT, time zone ID, and rules for starting and ending the daylight time. |
Here, time0mode
specifies the mode of the starting time, and time1mode
specifies the mode of the ending time. Valid mode
values include:
Field |
Description |
Constant for a mode of start or end time specified
as standard time. |
|
Constant for a mode of start or end time specified
as UTC. |
|
Constant for a mode of start or end time specified
as wall clock time. |
The time mode indicates how the time values are
interpreted. The default mode used by the other constructors is WALL_TIME.
Method |
Description |
clone() |
Returns a clone of
this SimpleTimeZone instance. |
Compares the equality of
two SimpleTimeZone objects. |
|
Returns the amount of time in milliseconds that the
clock is advanced during daylight saving time. |
|
getOffset(int era,
int year, int month, int day, int dayOfWeek,
int millis) |
Returns the difference in milliseconds between local
time and UTC, taking into account both the raw offset and the effect of
daylight saving, for the specified date and time. |
getOffset(long date) |
Returns the offset of this time zone from UTC at the
given time. |
Gets the GMT offset for this time zone. |
|
hashCode() |
Generates the hash code for the SimpleDateFormat
object. |
hasSameRules(TimeZone other) |
Returns true if this zone has the same
rules and offset as another zone. |
inDaylightTime(Date date) |
Queries if the given date is in daylight saving time. |
Returns true if
this SimpleTimeZone observes Daylight Saving Time. |
|
setDSTSavings(int millisSavedDuringDST) |
Sets the amount of time in milliseconds that the
clock is advanced during daylight saving time. |
setEndRule(int endMonth, int endDay,
int endTime) |
Sets the daylight saving time end rule to a fixed
date within a month. |
setEndRule(int endMonth, int endDay,
int endDayOfWeek, int endTime) |
Sets the daylight saving time end rule. |
setEndRule(int endMonth, int endDay,
int endDayOfWeek, int endTime, boolean after) |
Sets the daylight saving time end rule to a weekday
before or after the given date within a month, e.g., the first Monday on or
after the 8th. |
setRawOffset(int offsetMillis) |
Sets the base time zone offset to GMT. |
setStartRule(int startMonth, int startDay,
int startTime) |
Sets the daylight saving time start rule to a fixed
date within a month. |
setStartRule(int startMonth, int startDay,
int startDayOfWeek, int startTime) |
Sets the daylight saving time start rule. |
setStartRule(int startMonth, int startDay,
int startDayOfWeek, int startTime, boolean after) |
Sets the daylight saving time start rule to a
weekday before or after the given date within a month, e.g., the first Monday
on or after the 8th. |
setStartYear(int year) |
Sets the daylight saving time starting year. |
toString() |
Returns a string representation of this time zone. |
Queries if this time zone uses daylight saving time. |
Locale
The Locale class is instantiated to
produce objects that describe a geographical or cultural region. It is one of several classes that
provide you with the ability to write programs that can execute in different
international environments. The formats used to display dates, times, and numbers are different in
various regions. Internationalization is a large topic that is beyond the scope
of this course. However, many programs will only need to deal with its basics,
which include setting the current locale. The
Locale class
defines the following constants that are useful for dealing with several common
locales:
Constructors of this class are:
Constructor |
Description |
Construct a locale from a
language code. |
|
Construct a locale from
language and country. |
|
Construct a locale from
language, country and variant. |
Methods of this class are:
Method |
Description |
clone() |
Overrides Cloneable. |
Returns true if this Locale is equal to
another object. |
|
forLanguageTag(String languageTag) |
Returns a locale for the specified IETF BCP
47 language tag string. |
Returns an array of all installed locales. |
|
Returns the country/region code for this
locale, which should either be the empty string, an uppercase ISO 3166 2-letter
code, or a UN M.49 3-digit code. |
|
Gets the current value of the default locale
for this instance of the Java Virtual Machine. |
|
getDefault(Locale.Category category) |
Gets the current value of the default locale
for the specified Category for this instance of the Java Virtual Machine. |
Returns a name for the locale's country that
is appropriate for display to the user. |
|
getDisplayCountry(Locale inLocale) |
Returns a name for the locale's country that
is appropriate for display to the user. |
Returns a name for the locale's language
that is appropriate for display to the user. |
|
getDisplayLanguage(Locale inLocale) |
Returns a name for the locale's language
that is appropriate for display to the user. |
Returns a name for the locale that is
appropriate for display to the user. |
|
getDisplayName(Locale inLocale) |
Returns a name for the locale that is
appropriate for display to the user. |
Returns a name for the the locale's script
that is appropriate for display to the user. |
|
getDisplayScript(Locale inLocale) |
Returns a name for the locale's script that
is appropriate for display to the user. |
Returns a name for the locale's variant code
that is appropriate for display to the user. |
|
getDisplayVariant(Locale inLocale) |
Returns a name for the locale's variant code
that is appropriate for display to the user. |
getExtension(char key) |
Returns the extension (or private use) value
associated with the specified key, or null if there is no extension
associated with the key. |
Returns the set of extension keys associated
with this locale, or the empty set if it has no extensions. |
|
Returns a three-letter abbreviation for this
locale's country. |
|
Returns a three-letter abbreviation of this
locale's language. |
|
Returns a list of all 2-letter country codes
defined in ISO 3166. |
|
Returns a list of all 2-letter language
codes defined in ISO 639. |
|
Returns the language code of this Locale. |
|
Returns the script for this locale, which
should either be the empty string or an ISO 15924 4-letter script code. |
|
Returns the set of unicode locale attributes
associated with this locale, or the empty set if it has no attributes. |
|
Returns the set of Unicode locale keys
defined by this locale, or the empty set if this locale has none. |
|
Returns the Unicode locale type associated
with the specified Unicode locale key for this locale. |
|
Returns the variant code for this locale. |
|
hashCode() |
Override hashCode. |
setDefault(Locale.Category category, Locale newLocale) |
Sets the default locale for the specified
Category for this instance of the Java Virtual Machine. |
setDefault(Locale newLocale) |
Sets the default locale for this instance of
the Java Virtual Machine. |
Returns a well-formed IETF BCP 47 language
tag representing this locale. |
|
toString() |
Returns a string representation of
this Locale object, consisting of language, country, variant,
script, and extensions. |
Currency
The
Currency class of java.util package simply a way
to represent a currency. Currencies are identified by their ISO 4217 currency
codes. Currencies can be represented in the code in two ways: a three-letter
alphabetic code (e.g., INR for Indian Rupees, JPY for Japan Yen, etc.);
alternatively, a three-digit numeric code are also known.
This
class has been designed so that there’s never more than one Currency instance
for any given currency. Because of this design, the Currency class has
no public constructor. Instead, you can obtain a Currency instance using
the getInstance methods. This behavior may be related to another commonly used
class Calendar which follows the same principle.
The
methods supported by Currency are
shown in below.
Method |
Description |
Gets the set of available
currencies. |
|
Gets the ISO 4217 currency code
of this currency. |
|
Gets the default number of
fraction digits used with this currency. |
|
Gets the name that is suitable
for displaying this currency for the default DISPLAY locale. |
|
getDisplayName(Locale locale) |
Gets the name that is suitable
for displaying this currency for the specified locale. |
getInstance(Locale locale) |
Returns the Currency instance
for the country of the given locale. |
getInstance(String currencyCode) |
Returns
the Currency instance for the given currency code. |
Returns the ISO 4217 numeric
code of this currency. |
|
Gets the symbol of this
currency for the default DISPLAY locale. |
|
Gets the symbol of this
currency for the specified locale. |
|
toString() |
Returns the ISO 4217 currency
code of this currency. |
Example 17.8:
Illustration of currency objects
// The following program demonstrates Currency:
import java.util.*;
class CurrencyDemo {
public static void main(String args[]) {
Currency c;
Currency c = Currency.getInstance(Locale.US);
System.out.println("USD Symbol: " + c.getSymbol());
System.out.println("Default fractional digits: " +
c.getDefaultFractionDigits());
// Use of getInstance() methods
Currency
c1 = Currency.getInstance("AUD"); //Australian Dollar
Currency
c2 = Currency.getInstance("JPY"); //Japan Yen
Currency
c3 = Currency.getInstance("INR"); //Indian rupees
// Use of getSymbol() method
System.out.println("AUD Symbol :
"+c1.getSymbol());
System.out.println("JPY
Symbol : "+c2.getSymbol());
System.out.println("INR
Symbol : "+c3.getSymbol());
}
}
The output is shown here:
USD Symbol: $
Default fractional digits: 2
AUD Symbol: $
JPY Symbol: Y
INR Symbol: R
Java
Cursors
When you are dealing with a collection, you have to perform CRUD
operations. The CRUD operations in JCF implies the following.
Create: Adding new elements to Collection object.
Read: Retrieving elements from Collection object.
Update: Updating or setting existing elements in Collection
object.
Delete: Removing elements from Collection object.
You
will see there are many classes in the JCF loaded with many methods in each to
accomplish the CRUD operations. In
addition to the CRUD operations, it is also an important aspect to traverse or
visit each element in the cursor. For this very reason, Java developer
introduces a concept called Java cursor. A Java cursor is a pointer (more
precisely loop indicator), which is used to iterate (loop or cycle or visit) or
traverse or retrieve collection elements one by one. Java supports the
following four different cursors.
·
Enumeration
·
Iterator
·
ListIterator
·
Spliterator
Let us learn each of the above-mentioned Java cursors, in
details with appropriate illustrations.
Enumeration interface
It
is an interface used to get elements of legacy collections (Vector, Hashtable).
Enumeration is the first iterator introduced in JDK 1.0. The interface Enumeration has the following
methods declared in it.
Method |
Description |
public boolean hasMoreElements(); |
Tests
if this enumeration contains more elements. |
public Object nextElement(); |
Returns
the next element of this enumeration. |
Table 18.1: The methods defined in
Enumeration interface
The
Collection class defined in java.util package has its own implementation of the
interface Enumeration.
Enumerations are also used to specify the input streams to a
SequenceInputStream. You can create Enumeration object by calling elements()
method of Vector class on any Vector object. For example, if v denotes an
object of the class Vector class, then e is an object of type Enumeration
referring to v is:
Enumeration e = v.elements();
Example
18.1.
The following example, illustrates the Enumeration Java cursors
to traverse a collection of type Vector.
//
Java program to demonstrate Enumeration
import java.util.Enumeration;
import java.util.Vector;
public class EnumerationTest {
public static void main(String[] args) {
//
Create a vector and print its contents
Vector
v = new Vector();
for (int i = 0; i < 10; i++)
v.addElement(i);
System.out.println(v);
//
Declare an enumerator to the collection v
Enumeration
e = v.elements(); // At the beginning e points to
// index just
before the first element in v
while (e.hasMoreElements()) {// Enumerate
each element one-by-one
int i =
(Integer)e.nextElement(); //Moving cursor to next element
System.out.print(i
+ " "); // Print the current
element
}
}
}
Java
Enumeration limitations
·
It is applicable to only Collection of legacy classes, like
Vector and HashTable.
·
Compare to other Cursors, it has very lengthy method names:
hasMoreElements() and nextElement().
·
In CRUD pperations, it supports only read operation. It does
not support creagte, update and delete operations.
·
It supports only forward direction iteration. That’s why it
is also known as uni-directional cursor.
We will discuss about Iterator with some suitable examples
in this post.
Iterator interface
The
limitations in Enumeration interface had been addressed in JDK 1.2, and
introduced a better Java cursor called Iterator. It is a universal iterator as
you can apply it to any Collection object like Set, List, Queue, Deque and also
in all implemented classes of Map interface. By using Iterator, you can perform
both read and remove operations. The
Ierator interface defines three methods as listed in Table 2. The Iterator
interface is fully implemented by Collection classes.
Method |
Description |
public boolean hasNext(); |
Returns
true if the iterator has more elements. |
public Object next(); |
Returns
the next element in the iterator. |
public void remove(); |
Remove
the next element in the iterator. This method can be called only once per
call to next(). |
Table 18.2: The
methods defined in Iterator interface
Example
18.2.
The following program shows an example of Iterator obeject
with ArrayList class.
import java.util.*;
public class IteratorDemo {
public static void main(String[] args) {
ArrayList<Integer>
al = new ArrayList<Integer>();
for (int i = 0; i < 10; i++)
al.add(i);
System.out.println(al);
Iterator
itr = al.iterator();
// The cursor at the beginning
of the first element
while (itr.hasNext()) { // Iterate over each element in al
int i = itr.next(); // Read the current element
System.out.print(i
+ " ");
if (i % 2 != 0)
itr.remove();
// Removing odd elements
}
System.out.println();
System.out.println(al);
}
}
Example 18.3.
Be
careful. You cannot add or remove elements to the collection while using iterator
over it. Following example, will give a run-time exception.
import
java.util.*;
public
class ErrorWithIterator {
public static void main(String args[]){
ArrayList<String> books = new
ArrayList<String>();
books.add("C");
books.add("C++");
books.add("Java”);
for(String obj : books) {
System.out.println(obj);
//We are adding element while iterating
list
books.add("C++");
}
Iterator itr = books.iterator();
while (itr.hasNext()) {
String
b = itr.next();
System.out.print(b
+ " ");
books.add("Python"); // You cannot do it!
books.remove(“C”), // You cannot do it!!
}
}
}
Java
Iterator limitations
·
It supports only forward direction iteration. That is, like
Enumerator, it is also a uni-directional cursor.
·
Only read and
remove is possible. Replacement and addition of new element is not supported by
Iterator
ListIterator interface
It
is only applicable for List collection implemented classes like arraylist,
linkedList, etc. It provides bi-directional iteration. This cursor has more
functionality than iterator. ListIterator interface extends Iterator interface.
So all three methods of Iterator interface are available for ListIterator. In
addition, there are six more methods, which are listed in Table 3.
Description |
|
void add(E obj) |
Inserts obj into
the list in front of the element
that will be returned by the next call to next( ). |
default void forEachRemaining( Consumer<? super E>
action) |
The action specified by action is
executed on each unprocessed element in the collection. (Added
by JDK 8.) |
boolean hasNext( ) |
Returns true if there
is a next element. Otherwise, returns false. |
boolean hasPrevious( ) |
Returns true if there is a previous element. Otherwise, returns
false. |
E next( ) |
Returns the next
element. A NoSuchElementException is thrown if there is not a next element. |
int nextIndex( ) |
Returns the index of the next
element. If there is not a next element, returns the size of the list. |
E previous( ) |
Returns the previous element. A NoSuchElementException is thrown if there is not a previous element. |
int previousIndex( ) |
Returns the index of the previous element. If there
is not a previous element, returns –1. |
void remove( ) |
Removes the current element
from the list.
An IllegalStateException is thrown
if remove(
) is called before next( ) or previous( ) is invoked. |
void set(E obj) |
Assigns obj to the current
element. This is the element
last returned by a call to either next( ) or previous( ). |
Table 18.3: The
methods defined in ListIterator interface
Example
18.4.
The following program shows an example of ListIterator with
ArrayList class.
import
java.util.*;
class
ListIteratorDemo {
public static void main(String args[]) {
// Create an array list.
ArrayList<String> al = new
ArrayList<String>();
// Add elements to the array list.
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
// Use iterator to display contents of al.
System.out.print("Original contents of
al: ");
Iterator<String> itr = al.iterator();
while(itr.hasNext()) {
String element = itr.next();
System.out.print(element +
" ");
}
System.out.println();
// Modify objects being iterated.
ListIterator<String> litr = al.listIterator();
while(litr.hasNext()) {
String element =
litr.next();
litr.set(element +
"+");
}
System.out.print("Modified contents of
al: ");
// Now, display the list backwards.
System.out.print("Modified list
backwards: ");
while(litr.hasPrevious()) {
String element =
litr.previous();
System.out.print(element +
" ");
}
System.out.println();
}
}
Note:
If
you won’t be modifying the contents of a collection or obtaining elements in
reverse order, then the for-each version of the for loop is often a more
convenient alternative to cycling through a collection than is using an
iterator. Recall that the for can cycle through any collection of objects that
implement the Iterable interface. Because all of the collection classes
implement this interface, they can all be operated upon by the for.
Example 18.5.
The
following example uses the for-each for loop to cycle through a collection.
import java.util.*;
class ForEachLoopDemo {
public static
void main(String args[]) {
// Create an
array list for integers.
ArrayList<Integer>
vals = new ArrayList<Integer>();
// Add values to
the array list.
vals.add(1);
vals.add(2);
vals.add(3);
vals.add(4);
vals.add(5);
// Use for loop
to display the values.
System.out.print("Contents
of vals: ");
for(int v : vals)
System.out.print(v
+ " ");
System.out.println();
// Now, sum the
values by using a for loop.
int sum = 0;
for(int v : vals)
sum += v;
System.out.println("Sum
of values: " + sum);
}
}
Note:
·
Clearly the three methods that ListIterator inherits from Iterator
(hasNext(), next(), and remove()) do exactly the same thing in both interfaces.
The hasPrevious() and the previous operations are exact analogues of hasNext()
and next(). The former operations refer to the element before the (implicit)
cursor, whereas the latter refer to the element after the cursor. The previous
operation moves the cursor backward, whereas next moves it forward.
·
ListIterator has no current element; its cursor position always
lies between the element that would be returned by a call to previous() and the
element that would be returned by a call to next()
·
Please note that initially any iterator reference will point to
the index just before the index of first element in a collection.
·
We don’t create objects of Enumeration, Iterator, ListIterator
because they are interfaces. We use methods like elements(), iterator(),
listIterator() to create objects. These methods have anonymous Inner classes
that extends respective interfaces and return this class object. This can be
verified by below code. For more on inner class refer
Example 18.6.
The following Java program demonstrates iterators references of
different types to the same collection.
import java.util.Enumeration;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Vector;
public class JavaCurorsTest {
public static void main(String[] args) {
Vector
v = new Vector();
//
Create three iterators
Enumeration
e = v.elements();
Iterator
itr = v.iterator();
ListIterator
ltr = v.listIterator();
//
Code to use the iterators
}
}
Limitations of ListIterator
It is the most powerful iterator but it is only applicable
for List implemented classes, so it is not a universal iterator.
Example 18.7.
This
program illustrates the application of iterator with a collection of generic
data type. Here, we have considered Employee class for example. Further, you
note how you can customize the iterator interface with your own.
public class Employee {
private int empid;
private String ename;
private String designation;
private double salary;
public Employee(int empid,String ename,String
designation,double salary){
this.empid = empid;
this.ename = ename;
this.designation = designation;
this.salary = salary;
}
public int getEmpid() {
return empid;
}
public String getEname() {
return ename;
}
public String getDesignation() {
return designation;
}
public double getSalary() {
return salary;
}
//This shows how to print an
element of custom type using toString()
@Override
public String toString(){
return
empid + "\t" + ename + "\t" + designation + "\t"
+ salary;
}
}
This
follows the definition of main class.
import java.util.*;
public class Employees implements Iterable{
private List<Employee> emps = null;
public Employees(){
emps = new ArrayList<&glt;();
emps.add(new Employee(101,"Ram","Professor",
250000L));
emps.add(new Employee(102,"Rahim","Engineer",
300000L));
emps.add(new Employee(1003,"Jonny","Doctor",
350000L));
}
@Override
public
Iterator<Employee> iterator() {
return
emps.iterator();
}
}
public class EmployeesTester
{
public static void main(String[] args) {
Employees emps = new Employees();
for(Employee emp : emps){
System.out.println(emp);
}
}
}
Splitearotr Interface
Spliterator,
like other Java cursors, is for traversing the elements of a collection. Unlike
other cursors, it can travesre both in parallel as well as sequential manner.
The name is so because it is actually splitting + iterator to accomplish a
parallel traversing. It was included in JDK 8 and is defined by the Spliterator
interface. Compare to other cursors, it offers substantially more
functionality. Perhaps the most important aspect of Spliterator is its ability
to provide support for parallel iteration of portions of the sequence and hence
providing parallel programming.
The
Spliterator defines 8 methods which are listed in Table 4. All methods are duly
implemented in Collection classes.
Method |
Description |
int characteristics( ) |
Returns the
characteristics of the
invoking spliterator, encoded into an integer. |
long estimateSize( ) |
Estimates the number
of elements left
to iterate and returns the result. Returns Long.MAX_VALUE if
the count cannot be
obtained for any reason. |
default void forEachRemaining( Consumer<? super T> action) |
Applies action to
each unprocessed element
in the data source. |
default Comparator<? super
T> getComparator( ) |
Returns the comparator used
by the invoking spliterator or null if
natural ordering is used. If the sequence is unordered, IllegalStateException is
thrown. |
default long getExactSizeIfKnown( ) |
If the invoking spliterator is sized, returns
the number of elements left to iterate. Returns –1 otherwise. |
default
boolean hasCharacteristics(int
val) |
Returns true if the invoking spliterator has the characteristics passed in val. Returns false otherwise. |
boolean tryAdvance( Consumer<? super T> action) |
Executes action on
the next element in the iteration. Returns true if
there is a next element. Returns false if
no elements remain. |
Spliterator<T> trySplit( ) |
If possible, splits the invoking spliterator,
returning a reference to a new spliterator for the partition. Otherwise, returns
null. Thus,
if successful, the original spliterator iterates over one portion of the sequence and the returned spliterator iterates over the other portion. |
Table 18.4: The methods defined in Spliteraor
Example 18.8:
The
following program provides a simple example of Spliterator. Notice that the
program demonstrates both tryAdvance( ) and forEachRemaining( ). Also notice
how these methods combine the actions of Iterator’s next( ) and hasNext( )
methods into a single call.
import java.util.*;
class SpliteratorDemo {
public static
void main(String args[]) {
// Create an
array list for doubles.
ArrayList<Double>
vals = new ArrayList<>();
// Add values to
the array list.
vals.add(1.0);
vals.add(2.0);
vals.add(3.0);
vals.add(4.0);
vals.add(5.0);
// Use
tryAdvance() to display contents of vals.
System.out.println("Contents
of vals: ");
Spliterator<Double>
spltitr = vals.spliterator();
while(spltitr.tryAdvance((n)->
System.out.println(n)));
System.out.println();
// Create new
list that contains square roots.
spltitr =
vals.spliterator();
ArrayList<Double>
sqrs = new ArrayList<>();
while(spltitr.tryAdvance((n)
-> sqrs.add(Math.sqrt(n))));
// Use
forEachRemaining() to display contents of sqrs.
System.out.print("Contents
of sqrs:\n");
spltitr =
sqrs.spliterator();
spltitr.forEachRemaining((n)
-> System.out.println(n));
System.out.println();
}
}
Example 18.9.
Another
example is given below demonstrating the utility of other methods methods of
Spliterator.
import java.util.*;
public class SpliteratorDemo {
public static void main(String[] args) {
//
Create an array list for doubles.
ArrayList<Integer>
al = new ArrayList<>();
//
Add values to the array list.
al.add(1);
al.add(2);
al.add(-3);
al.add(-4);
al.add(5);
//
Obtain a Stream to the array list.
Stream<Integer>
str = al.stream();
//
getting Spliterator object on al
Spliterator<Integer>
splitr1 = str.spliterator();
//
estimateSize method
System.out.println("estimate
size : " +
splitr1.estimateSize());
//
getExactSizeIfKnown method
System.out.println("exact
size : " +
splitr1.getExactSizeIfKnown());
//
hasCharacteristics and characteristics method
System.out.println(splitr1.hasCharacteristics(splitr1.characteristics()));
System.out.println("Content
of arraylist :");
//
forEachRemaining method
splitr1.forEachRemaining((n)
-> System.out.println(n));
//
Obtaining another Stream to the array list.
Stream<Integer>
str1 = al.stream();
splitr1
= str1.spliterator();
//
trySplit() method
Spliterator<Integer>
splitr2 = splitr1.trySplit();
//
If splitr1 could be split, use splitr2 first.
if(splitr2
!= null) {
System.out.println("Output
from splitr2: ");
splitr2.forEachRemaining((n)
-> System.out.println(n));
}
//
Now, use the splitr
System.out.println("\nOutput
from splitr1: ");
splitr1.forEachRemaining((n)
-> System.out.println(n));
}
}
Have
a look at tryAdvance() method.It performs an action on the next element and
then advances the iterator. It is shown here:
boolean
tryAdvance(Consumer<? super T> action)
Here,
action specifies the action that is executed on the next element in the iteration
and Consumer is a functional interface that applies an action to an object. It
is a generic functional interface declared in java.util.function. It has only
one abstract method, accept( ), which is
shown
here:
void
accept(T objRef)
here
T is type of object reference.
For
implementing our action, we must implement accept method.To implement accept
method, here we use lambda expression .This will be more clear from below
example.
How
to use Spliterator with Collections: Using Spliterator for basic iteration
tasks is quite easy, simply call tryAdvance( ) until it returns false.
Example 18.10.
Java
program to demonstrate simple Spliterator using tryAdvance method
import java.util.ArrayList;
import java.util.Spliterator;
public class SpliteratorDemo
{
public static void main(String[] args)
{
//
Create an array list for doubles.
ArrayList<Integer>
al1 = new ArrayList<>();
//
Add values to the array list.
al1.add(1);
al1.add(2);
al1.add(-3);
al1.add(-4);
al1.add(5);
//
Use tryAdvance() to display(action) contents of arraylist.
System.out.print("Contents
of arraylist:\n");
//
getting Spliterator object on al1
Spliterator<Integer>
splitr = al1.spliterator();
//
Use tryAdvance() to display(action) contents of arraylist.
//
Notice how lambda expression is used to implement accept method
//
of Consumer interface
while(splitr.tryAdvance((n)
-> System.out.println(n)));
//
Use tryAdvance() for getting absolute values(action) of contents of arraylist.
//
Create new list that contains absolute values.
ArrayList<Integer>
al2 = new ArrayList<>();
splitr
= al1.spliterator();
//
Here our action is to get absolute values
//
Notice how lambda expression is used to implement accept method
//
of Consumer interface
while(splitr.tryAdvance((n)
-> al2.add(Math.abs(n))));
System.out.print("Absolute
values of contents of arraylist:\n");
//
getting Spliterator object on al2
splitr
= al2.spliterator();
while(splitr.tryAdvance((n)
-> System.out.println(n)));
}
}
Notice
how tryAdvance( ) consolidates the purposes of hasNext( ) and next( ) provided
by Iterator into a single method in above example. This improves the efficiency
of the iteration process.
In
some cases, you might want to perform some action on each element collectively,
rather than one at a time. To handle this type of situation, Spliterator
provides the forEachRemaining( ) method, it is generally used in cases
involving streams. This method applies action to each unprocessed element and
then returns.